package com.mera.tektronix.csviewer.services

import org.apache.commons.logging.LogFactory
import org.springframework.context.MessageSource

import com.mera.tektronix.csviewer.common.api.*
import com.mera.tektronix.csviewer.common.dto.*
import com.mera.tektronix.csviewer.common.exception.*
import com.mera.tektronix.csviewer.domain.*

class ProjectService {
	static transactional = true
	private static final log = LogFactory.getLog(ProjectService.class)
	
	MessageSource messageSource
	IProjectService projectServiceProxy
	IDepartmentService departmentServiceProxy
	
	def getList(params) {
		log.debug(params)
		
		return projectServiceProxy.getListByDepartmentId(Long.valueOf(params.id)).collect{[
			id   : ("_PRJ_" + it.id),
			text : it.name
		]}
	}
	
	def getAllList() {		
		return projectServiceProxy.getList().collect {[
			id   : it.id,
			text : it.name,
			department  : it.departmentName
		]}
	}
	
	def getElement(params) {
		log.debug(params)
		
		ProjectDto prj = null;
		
		try {
			prj = projectServiceProxy.getProjectById(Long.valueOf(params.id));
		} catch(Exception ex) {
			return [
				success      : 'false',
				errorMessage : ex.getLocalizedMessage()
			];
		}
		
		if(prj == null) {
			return [
				success      : 'false',
				errorMessage : "No Project has been found."
			]
		}
		
		return [
			id           : prj.id,
			name         : prj.name,
			email        : prj.email,
			phone        : prj.phone,
			department   : prj.departmentName,
			departmentId : prj.departmentId,
			success      : 'true'
		];
	}
	
	def addElement(params) {
		log.debug(params)
		
		DepartmentDto department = null;
		
		try {
			department = departmentServiceProxy.getDepartmentById(Long.valueOf(params.department));
		} catch(Exception ex) {
			return [
				success      : 'false',
				errorMessage : ex.getLocalizedMessage()
			];
		}
		
		if(department == null) {
			return [
				success      : 'false',
				errorMessage : "No Department has been found."
			]
		} else {
			ProjectDto proj = new ProjectDto();
			
			if(params.id != null) proj.id = Long.valueOf(params.id);
			proj.name = params.name;
			proj.email = params.email;
			proj.phone = params.phone;
			proj.departmentId = department.id;
			
			try {
				projectServiceProxy.addProject(proj);
			} catch(LogicException lex) {
				def errorList = lex.getErrors();
				
				return [
					success      : 'false',
					errors       : errorList
				]
			}
		}
		
		return [
			success : 'true'
		]
	}
	
	def updateElement(params) {		
		return addElement(params);
	}
	
	def deleteElement(params) {
		log.debug(params)
				
		try {
			projectServiceProxy.deleteProject(Long.valueOf(params.id));
		} catch(Exception ex) {
			return [
				success      : 'false',
				errorMessage : ex.getLocalizedMessage()
			];
		}
		
		return [success : 'true'];
	}
}
